import {Injectable} from '@angular/core';
import {Observable} from "rxjs";
import {HttpProvider} from "@providers/http";
import {NativeProvider} from "@providers/natives/native";
import {MapProvider} from "@providers/map";
import {DialogProvider} from "@providers/dialog";
import {StorageProvider} from "@providers/storage";
import {AuthGuardProvider} from "@providers/auth-guard";
import {Diagnostic} from "@ionic-native/diagnostic";


declare let plugins;
declare let cordovaNaviMap;

/*
  Generated class for the LocationProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class LocationProvider {

  map: any;//地图对象
  timer: any;//定时器
  ms: any = {
    "lat": null,
    "lng": null,
  };

  constructor(private dialog: DialogProvider,
              private diagnostic: Diagnostic,
              private storageService: StorageProvider,
              private http: HttpProvider,
              private authGuard: AuthGuardProvider,
              private native: NativeProvider,
              private mapService: MapProvider) {
  }

  /**
   * 获得用户当前坐标
   */
  getUserLocation() {
    return Observable.create(observer => {
      if (this.native.isMobile()) {
        this.assertLocationService().subscribe(res => {
          if (res) {
            this.assertLocationAuthorization().subscribe(res => {
              if (res) {
                this.getLocation().subscribe(data => {
                  console.info(data);
                  observer.next({'lng': data.longitude.toFixed(5), 'lat': data.latitude.toFixed(5)});
                  observer.complete();
                }, error => {
                  observer.error(error);
                });
              }
            })
          }
        })
      } else {
        this.mapService.newMap();
        this.mapService.displayCurrentPosition().subscribe(data => {
          let currentLocation = {'lng': data.position.getLng(), 'lat': data.position.getLat()};
          //console.log('非手机环境,即测试环境返回固定坐标');
          observer.next(currentLocation);
          observer.complete();
        });
      }
    });
  }

  /**
   * 获取位置信息
   *
   */
  private getLocation() {
    return Observable.create(observer => {
      plugins.aMapLocationPlugin.getCurrentPosition(data => {
        observer.next(data);
        observer.complete();
      }, msg => {
        if (msg.indexOf('缺少定位权限') != -1) {
          this.dialog.showConfirm(() => {
            this.diagnostic.switchToSettings();
          }, '缺少定位权限,是否在手机设置或app权限管理中开启？');
        } else if (msg.indexOf('WIFI信息不足') != -1) {
          observer.error('定位失败,请确保连上WIFI或者关掉WIFI只开流量数据：' + msg);
        } else if (msg.indexOf('网络连接异常') != -1) {
          observer.error('网络连接异常,请检查您的网络是否畅通：' + msg);
        } else {
          observer.error('位置错误,错误消息:' + msg);
        }
      });
    });

  }

  /**
   * 检测app位置服务是否开启
   * @type {()=>any}
   */
  private assertLocationService = (() => {
    let enabledLocationService = false;//手机是否开启位置服务
    return () => {
      return Observable.create(observer => {
        if (enabledLocationService) {
          observer.next(true);
          observer.complete();
        } else {
          this.diagnostic.isLocationEnabled().then(enabled => {
            if (enabled) {
              enabledLocationService = true;
              observer.next(true);
              observer.complete();
            } else {
              enabledLocationService = false;
              this.dialog.showConfirm(() => {
                this.diagnostic.switchToLocationSettings();
              }, '您未开启位置服务,是否确定开启!');
            }
          }).catch(err => {
            observer.error('调用diagnostic.isLocationEnabled方法失败：' + err);
          });
        }
      });
    };
  })();

  /**
   * 检测app是否有定位权限
   * @type {()=>any}
   */
   assertLocationAuthorization = (() => {
    let locationAuthorization = false;
    return () => {
      return Observable.create(observer => {
        if (locationAuthorization) {
          observer.next(true);
          observer.complete();
        } else {
          this.diagnostic.isLocationAuthorized().then(res => {
            if (res) {
              locationAuthorization = true;
              observer.next(true);
              observer.complete();
            } else {
              locationAuthorization = false;
              this.diagnostic.requestLocationAuthorization('always').then(res => {//请求定位权限
                if (res == 'DENIED_ALWAYS') {//拒绝访问状态,必须手动开启
                  locationAuthorization = false;
                  this.dialog.showConfirm(() => {
                    this.diagnostic.switchToSettings();
                  }, '缺少定位权限,是否在手机设置或app权限管理中开启？');
                } else {
                  locationAuthorization = true;
                  observer.next(true);
                  observer.complete();
                }
              }).catch(err => {
                observer.error('调用diagnostic.requestLocationAuthorization方法失败：' + err);
              });
            }
          }).catch(err => {
            observer.error('调用diagnostic.isLocationAvailable方法失败：' + err);
          });
        }
      });
    };
  })();

  /**
   * 从高德地图打开导航
   * @param dlon 终点经度
   * @param dlat 终点纬度
   * @param dname 终点名称
   */
  public amapRoute(dlon: string, dlat: string, dname: string): Promise<string> {
    return new Promise<string>((resolve, reject) => {

      if (this.native.isAndroid()) {
        cordovaNaviMap.amapRoute('amapuri://route/plan/?sourceApplication=APP名称&dlat=' + dlat +
          '&dlon=' + dlon + '&dname=' + dname + '&dev=0&t=0',
          res => {
            resolve(res);
          },
          err => {
            reject(err);
          });
      } else {
        cordovaNaviMap.amapRoute('iosamap://path?sourceApplication=APP名称&dlat=' + dlat +
          '&dlon=' + dlon + '&dname=' + dname + '&dev=0&t=0',
          res => {
            resolve(res);
          }, err => {
            reject(err);
          });
      }
    });
  }

  /**
   * 从百度地图打开导航
   * @param dlon 终点经度
   * @param dlat 终点纬度
   * @param dname 终点名称
   */
  public bdmapRoute(dlon: string, dlat: string, dname: string): Promise<string> {
    return new Promise<string>((resolve, reject) => {

      if (this.native.isAndroid()) {
        cordovaNaviMap.bdmapRoute('baidumap://map/direction?destination=latlng:' + dlat +
          ',' + dlon + '|name:' + dname + '&mode=driving',
          res => {
            resolve(res);
          },
          err => {
            reject(err);
          });
      } else {
        cordovaNaviMap.bdmapRoute('baidumap://map/direction?destination=latlng:' + dlat +
          ',' + dlon + '|name:' + dname + '&mode=driving',
          res => {
            resolve(res);
          }, err => {
            reject(err);
          });
      }
    });
  }


  /**
   * 设置位置定时器，定时获取用户当前位置信息
   *
   * @param time 定时间隔，默认60秒
   */
  startLocationTimer(time: number = 60000) {
    return Observable.create(observer => {
      /*if (this.isMobile()){
          this.assertLocationService().subscribe(res => {
              if (res) {
                  this.assertLocationAuthorization().subscribe(res => {
                      if (res) {
                          plugins.aMapLocationPlugin.watchPosition(data => {
                              this.storageService.write('UserLocation', {'lng': data.longitude, 'lat': data.latitude});
                              observer.next(data);
                          }, err => {
                              observer.error(err);
                          }, time);
                      }
                  });
              }
          });

      }else{
          console.log('非手机环境,即测试环境返回固定坐标');
          this.storageService.write('UserLocation', {'lng': 114.275642, 'lat': 30.588644});
          observer.next({'lng': 114.275642, 'lat': 30.588644});
      }*/
      this.timer = Observable.timer(0, time).subscribe(() => {
        this.getUserLocation().subscribe(data => {
          console.info(data);
          this.storageService.write('UserLocation', {'lng': data.lng, 'lat': data.lat});
          observer.next(data);
          // observer.complete();
        })
      });

    });
  }

  /**
   * 关闭位置定时功能
   */
  stopLocation() {
    this.timer.unsubscribe();
    /*plugins.aMapLocationPlugin.clearWatch(success => {
        console.log(success);
    }, fail => {
        console.log(fail);
    });*/
  }


  /**
   * 将实时地址信息发送到服务器
   * 请在用户登陆后调用此方法
   */
  sendLocationToService(time = 60000) {
    this.startLocationTimer(time).subscribe(message => {
      if (message) {
        if (!this.authGuard.checkLogin() || !this.storageService.read('userInfo')['PARTYID']) {
          return;
        }
        console.info(message.lat, this.ms.LATITUDE, message.lat != this.ms.LATITUDE || message.lng != this.ms.LONGITUDE);
        if (message.lat != this.ms.LATITUDE || message.lng != this.ms.LONGITUDE) {
          this.http.post("/Inbound/invoke.do",
            {
              interfaceId: "csm.som.jcdy.qcfwtools.geopoint.insert",
              data: JSON.stringify({
                'position': this.storageService.read('UserLocation'),
                'partyId': this.storageService.read('userInfo')['PARTYID']
              })
            }).subscribe(message => {
            // JSON.parse(message).data

            this.ms = message.data;
            console.log(this.ms);
          });

        }
      }
    }, fail => {
    });
  }

  saveMasterP() {
    this.http.post("/Inbound/invoke.do",
      {
        interfaceId: "csm.som.jcdy.qcfwtools.geopoint.insert",
        data: JSON.stringify({
          'position': this.storageService.read('UserLocation'),
          'partyId': this.storageService.read('userInfo')['PARTYID']
        })
      }).subscribe(message => {
    });
  }

}
